﻿using EPiAbstractions.Common;
using EPiServer.Common;
using EPiServer.Common.Security;
using Moq;
using StructureMap.AutoMocking;
using Xunit;

namespace JoelAbrahamsson.MetaWeblog.Tests
{
    public class GetOrCreateUserAuthorTests
    {
        [Fact]
        public void GivenUserAuthorExistsForUser_GetOrCreateUserAuthor_ReturnsExistingUserAuthor()
        {
            IUser user = new Mock<IUser>().Object;
            UserAuthor existingAuthor = new Mock<UserAuthor>().Object;
            MoqAutoMocker<MetaWeblogHandler> metaWebLogHandlerAutoMocker = new MoqAutoMocker<MetaWeblogHandler>();
            Mock<IAuthorHandlerFacade> fakeAuthorHandlerFacade = Mock.Get(metaWebLogHandlerAutoMocker.Get<IAuthorHandlerFacade>());
            fakeAuthorHandlerFacade.Setup(authorHandler => authorHandler.GetUserAuthor(user)).Returns(existingAuthor);
            
            UserAuthor returnedAuthor = metaWebLogHandlerAutoMocker.ClassUnderTest.GetOrCreateUserAuthor(user);
            
            Assert.NotNull(returnedAuthor);
            Assert.Equal<UserAuthor>(existingAuthor, returnedAuthor);
        }

        [Fact]
        public void GivenNoUserAuthorExistsForUser_GetOrCreateUserAuthor_ReturnsNewUserAuthor()
        {
            IUser user = new Mock<IUser>().Object;
            UserAuthor newAuthor = new Mock<UserAuthor>().Object;
            MoqAutoMocker<MetaWeblogHandler> metaWebLogHandlerAutoMocker = new MoqAutoMocker<MetaWeblogHandler>();
            Mock<IAuthorHandlerFacade> fakeAuthorHandlerFacade = Mock.Get(metaWebLogHandlerAutoMocker.Get<IAuthorHandlerFacade>());
            fakeAuthorHandlerFacade.Setup(authorHandler => authorHandler.GetUserAuthor(user)).Returns((UserAuthor) null);
            fakeAuthorHandlerFacade.Setup(authorHandler => authorHandler.AddAuthor(It.IsAny<UserAuthor>())).Returns(newAuthor);

            UserAuthor returnedAuthor = metaWebLogHandlerAutoMocker.ClassUnderTest.GetOrCreateUserAuthor(user);

            fakeAuthorHandlerFacade.Verify(authorHandler => authorHandler.AddAuthor(It.IsAny<UserAuthor>()));
            Assert.NotNull(returnedAuthor);
            Assert.Equal<UserAuthor>(newAuthor, returnedAuthor);
        }
    }
}
